
from model import model
from log import log
from services import MyCache
from utils.MyUrl import MyUrl
import datetime

class articleDao:
    cache = MyCache().fsession()
    # 列出所有文章（分页）

    @cache.memoize(tag="article-all")
    def listAll(self,pageIndex,pageCount):
        pageIndex = int(pageIndex)
        pageCount = int(pageCount)
        page = (pageIndex-1)*pageCount
        try:
            articleList = model.article.objects().order_by("-updateDate").skip(page).limit(pageCount)
        except IOError:
            log.error(IOError)
        else:
            return articleList
    # 列出所有文章（不分页）

    @cache.memoize(tag="article-all-no-page")
    def listAllNoPage(self):
        try:
            articleList = model.article.objects().order_by("-updateDate")
        except IOError:
            log.error(IOError)
        else:
            return articleList

    # 列出文章基于导航id
    @cache.memoize(tag="article-nav-id")
    def listNavArt(self,navId,pageIndex,pageCount):
        page = (pageIndex-1)*pageCount
        try:
            articleList = model.article.objects(tid=navId).order_by("-updateDate").skip(page).limit(pageCount)
        except IOError:
            log.error(IOError)
        else:
            return articleList

    # 检查url是否重复转成拼音
    @staticmethod
    def checkPinYinUrlInDb(title):
        url = MyUrl.getPinYin(title)
        art = model.article.objects(url=url)
        if len(art) > 1:
            url = url +"_"+datetime.datetime.now().strftime("%Y_%m_%d_%s")
            return url
        return url

    # 清楚所有缓存
    def clearCache(self):
        cache = MyCache().fsession()
        cache.evict("article-all")
        cache.evict("article-all-no-page")
        cache.evict("article-nav-id")
        cache.evict("article-search")

